package com.ysd.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ysd.entity.Admin;

public class LoginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
//doFilter,过滤的核心,所有请求都会经过该方法
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;//将ServletRequest转化成HttpServletRequest
		HttpServletResponse res = (HttpServletResponse)response;
		HttpSession session = req.getSession();
		
		String url = req.getRequestURI();//获得访问路径
		System.out.println(url);
		Admin admin = (Admin)session.getAttribute("admin");//从session中取出admin数据
		if(url.endsWith("login.html") || url.endsWith(".css") || url.endsWith(".js") || url.endsWith(".jpg")) {
			chain.doFilter(req, res);//放行
		}else if (admin != null) {//登陆过了
			chain.doFilter(req, res);//放行
		} else {//没登录
			//res.sendRedirect("login.html");//重定向到login.html登陆页面
			res.sendRedirect("/kouhong/admin/login.html");
			//绝对路径和相对路径
		}
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
